<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<div class="panel panel-default operation" hidden>
    <div class="panel-heading title"></div>
    <div class="layui-card-body">
        <form class="layui-form " action="" lay-filter="info" style="width: 700px;margin-top: 10px">
            <input name="id" hidden/>
            <div class="layui-form-item">
                <label class="layui-form-label">bean名称</label>
                <div class="layui-input-block">
                    <input type="beanName" name="beanName" placeholder="请输入spring bean名称,如:testTask" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">参数</label>
                <div class="layui-input-block">
                    <input type="params" name="params" placeholder="请输入参数" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">cron表达式</label>
                <div class="layui-input-block">
                    <input type="cronExpression" id="cron" name="cronExpression" placeholder="请输入cron表达式,如:0 0 12 * * ?"
                           autocomplete="off" class="layui-input">
                    <button id="cronStr" style="position: absolute;top: 0;right: 24px;
                        cursor: pointer;" type="button" class="layui-btn">生成
                    </button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <input type="remark" name="remark" placeholder="请输入备注" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存</button>
                    <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="table_div">
    <div id="searchParam" shiro:hasPermission="sysJob:list">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" id="beanName" class="layui-input" autocomplete="off" placeholder="请输入bean名称">
            </div>

            <div class="layui-input-inline ">
                <button class="layui-btn" onclick="search()" id="search">查询</button>
                <button class="layui-btn" id="export">导出全部</button>
            </div>
        </div>

    </div>
    <table class="layui-table" id="showTable" lay-filter="showTable"></table>
</div>
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add" shiro:hasPermission="sysJob:add">添加</button>
        <button class="layui-btn layui-btn-sm" lay-event="batchDeleted" shiro:hasPermission="sysJob:delete">删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="pause" shiro:hasPermission="sysJob:pause">暂停</button>
        <button class="layui-btn layui-btn-sm" lay-event="resume" shiro:hasPermission="sysJob:resume">恢复</button>
        <button class="layui-btn layui-btn-sm" lay-event="run" shiro:hasPermission="sysJob:run">立即执行</button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" style="float: right" lay-event="jobLog"
                shiro:hasPermission="sysJob:list">任务日志
        </button>
    </div>
</script>
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="sysJob:update">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="sysJob:delete">删除</a>
</script>

</body>
</html>
<script src="/layui/layui.all.js"></script>
<script src="/js/core.util.js"></script>

<script>
    //获取token
    var token = CoreUtil.getData("access_token");
    //地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var tableIns1;
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;
    var tabId = new Date().getTime();


    layui.config({
        base: '/'
    }).extend({
        cron: "cron/cron",
    }).use(['table', 'layer', 'laydate', 'cron'], function () {
        cron = layui.cron;
        cron.render({
            elem: "#cronStr", // 绑定元素
            url:
                "https://www.fastmock.site/mock/58329c0ee61b03d6ce3ba0c1e2f13691/world/cron", // 获取最近运行时间的接口
            // value: $("#cron").val(), // 默认值
            done: function (cronStr) {
                console.log(cronStr);
                $("#cron").val(cronStr);
            },
        });

        //加载table
        tableIns1 = table.render({
            elem: '#showTable'
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , page: true //开启分页
            , url: '/sysJob/listByPage' //数据接口
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: '任务id', sort: true},
                    {field: 'beanName', title: 'spring bean名称', sort: true},
                    {field: 'params', title: '参数', sort: true},
                    {field: 'cronExpression', title: 'cron表达式', sort: true},
                    {
                        field: 'status', title: '任务状态', sort: true, templet: function (item) {
                            if (item.status === 1) {
                                return '  <input type="checkbox" lay-skin="switch" job_id = "' + item.id + '" lay-filter="jobSwitch"lay-text="正常|暂停">';
                            }
                            if (item.status === 0) {
                                return '  <input type="checkbox" lay-skin="switch" job_id = "' + item.id + '" lay-filter="jobSwitch" lay-text="正常|暂停" checked>';
                            }
                        }
                    },
                    {field: 'remark', title: '备注', sort: true},
                    {field: 'createTime', title: '创建时间', sort: true},
                    {width: 120, toolbar: "#tool", title: '操作'}
                ]
            ]
            , toolbar: '#toolbar'
        });

        //表头工具
        table.on('toolbar(showTable)', function (obj) {
            switch (obj.event) {
                case 'batchDeleted':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length == 0) {
                        layer.msg("请选择要批量删除的列");
                    } else {
                        var ids = [];
                        $(data).each(function (index, item) {
                            ids.push(item.id);
                        });
                        tipDialog(ids);
                    }
                    break;
                case 'pause':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length == 0) {
                        layer.msg("请选择要批量暂停的列");
                    } else {
                        var ids = [];
                        $(data).each(function (index, item) {
                            ids.push(item.id);
                        });
                        tipDialogPause(ids);
                    }
                    break;
                case 'resume':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length == 0) {
                        layer.msg("请选择要批量恢复的列");
                    } else {
                        var ids = [];
                        $(data).each(function (index, item) {
                            ids.push(item.id);
                        });
                        tipDialogResume(ids);
                    }
                    break;
                case 'run':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length == 0) {
                        layer.msg("请选择要批量运行的列");
                    } else {
                        var ids = [];
                        $(data).each(function (index, item) {
                            ids.push(item.id);
                        });
                        tipDialogRun(ids);
                    }
                    break;
                case 'add':
                    $(".table_div").hide();
                    $(".operation").show();
                    $(".title").html("新增");
                    $(".operation input[name=id]").val("");
                    $(".operation input[name=beanName]").val("");
                    $(".operation input[name=params]").val("");
                    $(".operation input[name=cronExpression]").val("");
                    $(".operation input[name=status]").val("");
                    $(".operation input[name=remark]").val("");
                    $(".operation input[name=createTime]").val("");
                    break;
                case 'jobLog':
                    window.parent.active.tabDelete(tabId);
                    window.parent.active.tabAdd("/index/sysJobLog", tabId, "定时任务日志")
                    window.parent.active.tabChange(tabId);
                    break;
            }
            ;
        });
        //列操作
        table.on('tool(showTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'del':
                    var ids = [];
                    ids.push(data.id);
                    tipDialog(ids);
                    break;

                case 'edit':
                    $(".table_div").hide();
                    $(".operation").show();
                    $(".title").html("编辑");
                    $(".operation input[name=id]").val(data.id);
                    $(".operation input[name=beanName]").val(data.beanName);
                    $(".operation input[name=params]").val(data.params);
                    $(".operation input[name=cronExpression]").val(data.cronExpression);
                    $(".operation input[name=status]").val(data.status);
                    $(".operation input[name=remark]").val(data.remark);
                    $(".operation input[name=createTime]").val(data.createTime);
                    break;
            }
        });

        //监听提交
        form.on('switch(jobSwitch)', function (data) {
            //获取所需属性值
            var job_id = data.elem.attributes['job_id'].nodeValue;
            var ids = [];
            ids.push(job_id);
            if (data.elem.checked) {
                CoreUtil.sendPost("/sysJob/resume", ids, function (res) {
                    layer.msg(res.msg, {time: 1000});
                });
            } else {
                CoreUtil.sendPost("/sysJob/pause", ids, function (res) {
                    layer.msg(res.msg, {time: 1000});
                });
            }
            return false;
        });

        //导出
        $('#export').on('click', function () {
            //原先分页limit
            var exportParams = {
                limit: 10000,
                beanName: $("#beanName").val()
            }
            CoreUtil.sendPost("/sysJob/listByPage", exportParams, function (res) {
                //初始化渲染数据
                if (res.data.records != null) {
                    table.exportFile(tableIns1.config.id, res.data.records, 'xls');
                }
            });
        });

        //删除
        var tipDialog = function (ids) {
            layer.open({
                content: "确定要删除么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendDelete("/sysJob/delete", ids, function (res) {
                        layer.msg(res.msg, {time: 1000}, function () {
                            search();
                        });
                    })
                }
            });
        };

        //暂停
        var tipDialogPause = function (ids) {
            layer.open({
                content: "确定要暂停么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendPost("/sysJob/pause", ids, function (res) {
                        layer.msg(res.msg, {time: 1000}, function () {
                            search();
                        });
                    });
                }
            });
        };

        //恢复
        var tipDialogResume = function (ids) {
            layer.open({
                content: "确定要恢复么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendPost("/sysJob/resume", ids, function (res) {
                        layer.msg(res.msg, {time: 1000}, function () {
                            search();
                        });
                    });
                }
            });
        };


        //立即执行
        var tipDialogRun = function (ids) {
            layer.open({
                content: "确定要立即执行么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendPost("/sysJob/run", ids, function (res) {
                        layer.msg(res.msg, {time: 1000}, function () {
                            search();
                        });
                    });
                }
            });
        };

        //返回
        $("#btn_cancel").click(function () {
            $(".table_div").show();
            $(".operation").hide();
            return false;
        });

        //监听保存
        form.on('submit(submit)', function (data) {
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendPost("/sysJob/add", data.field, function (res) {
                    $(".table_div").show();
                    $(".operation").hide();
                    search();
                });
            } else {
                CoreUtil.sendPut("/sysJob/update", data.field, function (res) {
                    $(".table_div").show();
                    $(".operation").hide();
                    search();
                });
            }

            return false;
        });
    });

    //执行查询
    function search() {
        //这里以搜索为例
        tableIns1.reload({
            where: { //设定异步数据接口的额外参数，任意设
                beanName: $("#beanName").val()
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    };
</script>